/* eslint-disable vue/no-mutating-props */
import { deepClone } from '../../utils/index'

const componentChild = {}
/**
 * 将./slots中的文件挂载到对象componentChild上
 * 文件名为key，对应JSON配置中的__config__.tag
 * 文件内容为value，解析JSON配置中的__slot__
 */
function initComponentChild() {
  const slotsFiles = require.context('./slots', false, /\.jsx$/)
  const keys = slotsFiles.keys() || []
  // console.log('keys', keys)
  keys.forEach(key => {
    const tag = key.replace(/^\.\/(.*)\.\w+$/, '$1')
    // console.log('tag', tag, 'key', key)
    const value = slotsFiles(key).default
    componentChild[tag] = value
  })
}
initComponentChild()

// console.log(componentChild)

function vModel(dataObject, confClone) {
  dataObject.props.value = confClone.__config__.defaultValue
  dataObject.on.input = (val) => {
    this.$emit('input', val)
    // console.log('confClone', confClone)
    if (confClone.on && confClone.on['update:value']) {
      confClone.on['update:value'](val)
    }
  }
}

function mountSlotFiles(h, confClone, children) {
  const childObjs = componentChild[confClone.__config__.tag]
  // console.log('componentChild', componentChild)
  // console.log('tag', confClone.__config__.tag)
  // console.log('childObjs', childObjs)
  if (childObjs) {
    Object.keys(childObjs).forEach(key => {
      const childFunc = childObjs[key]
      if (confClone.__slot__ && confClone.__slot__[key]) {
        // console.log('key', key)
        children.push(childFunc(h, confClone, key))
      }
    })
  }
  // console.log('children', children)
}

function emitEvents(confClone) {
  ['on', 'nativeOn'].forEach(attr => {
    const eventKeyList = Object.keys(confClone[attr] || {})
    eventKeyList.forEach(key => {
      const val = confClone[attr][key]
      // console.log('key', key, 'val', val)
      if (typeof val === 'string') {
        confClone[attr][key] = event => this.$emit(val, event)
      } else if (typeof val === 'function') {
        confClone[attr][key] = val.bind(this)
      }
    })
  })
  // console.log('confClone', confClone)
}

function buildDataObject(confClone, dataObject) {
  // console.log('confClone', confClone, 'dataObject', dataObject)
  Object.keys(confClone).forEach(key => {
    const val = confClone[key]
    if (key === '__vModel__') {
      vModel.call(this, dataObject, confClone)
    } else if (dataObject[key] !== undefined) {
      if (dataObject[key] === null ||
        dataObject[key] instanceof RegExp ||
        ['boolean', 'string', 'number', 'function'].includes(typeof dataObject[key])) {
        dataObject[key] = val
      } else if (Array.isArray(dataObject[key])) {
        dataObject[key] = [...dataObject[key], ...val]
      } else {
        dataObject[key] = { ...dataObject[key], ...val }
      }
    } else {
      dataObject.attrs[key] = val
    }
  })
  // 清理属性
  clearAttrs(dataObject)
}

function clearAttrs(dataObject) {
  delete dataObject.attrs.__config__
  delete dataObject.attrs.__slot__
  delete dataObject.attrs.__methods__
}

function makeDataObject() {
  // 深入数据对象：
  // https://cn.vuejs.org/v2/guide/render-function.html#%E6%B7%B1%E5%85%A5%E6%95%B0%E6%8D%AE%E5%AF%B9%E8%B1%A1
  return {
    class: {},
    attrs: {},
    props: {},
    domProps: {},
    nativeOn: {},
    on: {},
    style: {},
    directives: [],
    scopedSlots: {},
    slot: null,
    key: null,
    ref: null,
    refInFor: true
  }
}

export default {
  provide() {
    return {
      useConf: () => {
        let result = this.conf
        if (!result) result = { __config__: {}}
        if (!result.__config__) result.__config__ = {}
        return result
      },
      conf: this.conf
    }
  },
  props: {
    // 当前元素配置
    conf: {
      type: Object,
      required: true
    },
    // 当前表单
    form: {
      type: Object
    },
    // 所有表单
    forms: {
      type: Array
    }
  },
  render(h) {
    const dataObject = makeDataObject()
    const confClone = deepClone(this.conf)
    const children = this.$slots.default || []
    // console.log('conf', this.conf)
    // console.log('confClone', confClone)
    // console.log('this.$slots.default', this.$slots.default)
    // 如果slots文件夹存在与当前tag同名的文件，则执行文件中的代码
    mountSlotFiles.call(this, h, confClone, children)

    // 将字符串类型的事件，发送为消息
    emitEvents.call(this, confClone)
    // 将json表单配置转化为vue render可以识别的 “数据对象（dataObject）”
    buildDataObject.call(this, confClone, dataObject)
    // console.log('conf', this.conf)
    // console.log('tag', this.conf.__config__.tag)
    // console.log('dataObject', dataObject)
    // console.log('children', children)
    // console.log('card', this.card)
    const result = h(this.conf.__config__.tag, dataObject, children)
    return result
  }
}
